﻿using Nop.Admin.Models.Common;
using Nop.Admin.Models.XJ;
using Nop.Core;
using Nop.Core.Domain.Customers;
using Nop.Core.Domain.Directory;
using Nop.Core.Domain.XJ;
using Nop.Services.Common;
using Nop.Services.Customers;
using Nop.Services.Directory;
using Nop.Services.ExportImport;
using Nop.Services.Helpers;
using Nop.Services.Logging;
using Nop.Services.Media;
using Nop.Services.Security;
using Nop.Services.XJ;
using Nop.Web.Framework.Controllers;
using Nop.Web.Framework.Kendoui;
using Nop.Web.Framework.Mvc;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Web.Mvc;
using System.Web.UI.WebControls;

namespace Nop.Admin.Controllers
{
	public class MaintenanceController : BaseAdminController
	{
		#region Fields
		private readonly IPermissionService _permissionService;
		private readonly IPictureService _pictureService;
		private readonly IWorkContext _workContext;
		private readonly IDepartmentService _departmentService;
		private readonly ICustomerService _customerService;
		private readonly IGenericAttributeService _genericAttributeService;
		private readonly IXJPlaceService _xjPlaceService;
		private readonly IXJEquipmentCategoryService _xJEquipmentCategoryService;
		private readonly IXJEquipmentService _xJEquipmentService;
		private readonly IXJEquipmentStockService _xJEquipmentStockService;
		private readonly IXJEquipmentStockOutService _xJEquipmentStockOutService;
		private readonly IXJInspectionService _xJInspectionService;
		private readonly IXJInspectionPlanService _xJInspectionPlanService;
		private readonly IXJMaintenanceService _xJMaintenanceService;
		private readonly IXJMaintenanceDetailService _xJMaintenanceDetailService;
		private readonly IXJMaintenanceCustomersService _xJMaintenanceCustomersService;
		private readonly IXJMaintenanceCommentService _xJMaintenanceCommentService;
		private readonly IXJMaintenanceScheduleService _xJMaintenanceScheduleService;
		private readonly ICustomerActivityService _customerActivityService;
		private readonly IDateTimeHelper _dateTimeHelper;
		private readonly IExportManager _exportManager;
		private readonly ILogger _logger;
		#endregion

		#region Constructors
		public MaintenanceController(IPermissionService permissionService,
			IPictureService pictureService,
			IWorkContext workContext,
			IDepartmentService departmentService,
			ICustomerService customerService,
			IGenericAttributeService genericAttributeService,
			IXJPlaceService xjPlaceService,
			IXJEquipmentCategoryService xJEquipmentCategoryService,
			IXJEquipmentService xJEquipmentService,
			IXJEquipmentStockService xJEquipmentStockService,
			IXJEquipmentStockOutService xJEquipmentStockOutService,
			IXJInspectionService xJInspectionService,
			IXJInspectionPlanService xJInspectionPlanService,
			IXJMaintenanceService xJMaintenanceService,
			IXJMaintenanceDetailService xJMaintenanceDetailService,
			IXJMaintenanceCustomersService xJMaintenanceCustomersService,
			IXJMaintenanceCommentService xJMaintenanceCommentService,
			IXJMaintenanceScheduleService xJMaintenanceScheduleService,
			ICustomerActivityService customerActivityService,
			IDateTimeHelper dateTimeHelper,
			IExportManager exportManager,
			ILogger logger)
		{
			this._permissionService = permissionService;
			this._pictureService = pictureService;
			this._workContext = workContext;
			this._departmentService = departmentService;
			this._customerService = customerService;
			this._genericAttributeService = genericAttributeService;
			this._xjPlaceService = xjPlaceService;
			this._xJEquipmentCategoryService = xJEquipmentCategoryService;
			this._xJEquipmentService = xJEquipmentService;
			this._xJEquipmentStockService = xJEquipmentStockService;
			this._xJEquipmentStockOutService = xJEquipmentStockOutService;
			this._xJInspectionService = xJInspectionService;
			this._xJInspectionPlanService = xJInspectionPlanService;
			this._xJMaintenanceService = xJMaintenanceService;
			this._xJMaintenanceDetailService = xJMaintenanceDetailService;
			this._xJMaintenanceCustomersService = xJMaintenanceCustomersService;
			this._xJMaintenanceCommentService = xJMaintenanceCommentService;
			this._xJMaintenanceScheduleService = xJMaintenanceScheduleService;
			this._customerActivityService = customerActivityService;
			this._dateTimeHelper = dateTimeHelper;
			this._exportManager = exportManager;
			this._logger = logger;
		}
		#endregion

		#region Utilities

		[NonAction]
		protected virtual int GetLevel(Customer customer)
		{
			if (customer.IsAdmin())
				return (int)OperationLevelEnum.全部;

			var wxb = _departmentService.GetDepartmentByAbbr(SystemDepartmentyAbbrs.WXB);
			if (null != wxb)
			{
				if (customer.DepartmentId == wxb.Id)
				{
					if (customer.TeamId == 0)
						return (int)OperationLevelEnum.全部;
					else
						return (int)OperationLevelEnum.审核;
				}
			}

			return (int)OperationLevelEnum.编辑;
		}

		[NonAction]
		protected virtual void PrepareAllTypesModel(MaintenanceModel model)
		{
			if (model == null)
				throw new ArgumentNullException("model");

			model.AvailableDepartments.Add(new SelectMenuModel
			{
				name = "请选择",
				id = 0,
				open = true,
			});
			var departments = _departmentService.GetAllDepartments(showHidden: false);
			foreach (var d in departments)
				model.AvailableDepartments.Add(new SelectMenuModel { name = d.Name, id = d.Id, pId = d.PId });
			model.AvailableUsers.Add(new SelectListItem
			{
				Text = "全部",
				Value = "0"
			});
			if (model.ResponsibleTeamId > 0)
			{
				var users = _customerService.GetAllCustomers(
					//customerRoleIds: new[] { _customerService.GetCustomerRoleBySystemName(SystemCustomerRoleNames.Registered).Id },
					departId: model.ResponsibleTeamId).ToList();
				foreach (var u in users)
				{
					model.AvailableUsers.Add(new SelectListItem
					{
						Text = u.TrueName ?? u.Username,
						Value = u.Id.ToString(),
						Selected = model.ResponsibleTeamId == u.Id
					});
				}
			}
			model.HoursString = GetHoursString(model.Hours);
		}

		/// <summary>
		/// 工时
		/// </summary>
		/// <param name="minutes"></param>
		/// <returns></returns>
		[NonAction]
		private string GetHoursString(int minutes)
		{
			if (minutes <= 0)
				return "";

			if (minutes < 60)
				return string.Format("{0}分", minutes);

			int h = minutes / 60; // 计算小时数
			int m = minutes % 60; // 计算剩余的分钟数
			return string.Format("{0}时{1}", h, m > 0 ? m + "分" : "");
		}

		/// <summary>
		/// 事件处理平均工时
		/// </summary>
		/// <param name="minutes"></param>
		/// <returns></returns>
		[NonAction]
		private string GetPer(int minutes, int amount)
		{
			int per = minutes / amount; // 计算平均分钟数

			if (per <= 0)
				return "";

			if (per < 60)
				return string.Format("{0}分/次", per);

			int h = per / 60; // 计算小时数
			int m = per % 60; // 计算剩余的分钟数
			return string.Format("{0}时{1}/次", h, m > 0 ? m + "分" : "");
		}

		/// <summary>
		/// 月度工作效率
		/// </summary>
		/// <param name="minutes"></param>
		/// <param name="amount"></param>
		/// <returns></returns>
		[NonAction]
		private string GetEfficiency(int minutes, decimal monthHours)
		{
			if (minutes <= 0 || monthHours <= 0)
				return "";

			return string.Format("{0}%", ((minutes / (monthHours * 60)) * 100).ToString("0.00"));
		}

		[NonAction]
		private bool? GetBoolNullable(int id)
		{
			if (id == 1) return true;
			else if (id == 2) return false;
			return null;
		}

		#endregion

		#region List
		public ActionResult Index()
		{
			return RedirectToAction("List");
		}

		public virtual ActionResult List()
		{
			if (!_permissionService.Authorize(StandardPermissionProvider.ManageMaintenances))
				return AccessDeniedView();

			var model = new MaintenanceListModel();

			var customer = _workContext.CurrentCustomer;
			model.OperationLevel = GetLevel(customer);

			model.AvailableDepartments.Add(new SelectListItem
			{
				Text = "全部",
				Value = "0"
			});
			model.AvailableDepartmentMenus.Add(new SelectMenuModel
			{
				name = "全部",
				id = 0,
				open = true,
			});
			var departments = _departmentService.GetAllDepartments(showHidden: false);
			foreach (var d in departments)
				model.AvailableDepartmentMenus.Add(new SelectMenuModel { name = d.Name, id = d.Id, pId = d.PId });
			foreach (var d in departments.Where(m => m.PId == 0))
				model.AvailableDepartments.Add(new SelectListItem { Text = d.Name, Value = d.Id.ToString() });
			model.AvailableUsers.Add(new SelectListItem
			{
				Text = "全部",
				Value = "0"
			});
			var users = _customerService.GetAllCustomers().Select(x => new { id = x.Id, name = x.TrueName ?? x.Username }).ToList();
			foreach (var item in users)
				model.AvailableUsers.Add(new SelectListItem { Text = item.name, Value = item.id.ToString() });
			//if (model.OperationLevel == (int)OperationLevelEnum.审核)
			//{
			//	var users = _customerService.GetAllCustomers(
			//		departId: customer.TeamId
			//		).Select(x => new { id = x.Id, name = x.TrueName ?? x.Username }).ToList();
			//	foreach (var item in users)
			//		model.AvailableUsers.Add(new SelectListItem { Text = item.name, Value = item.id.ToString() });
			//}

			model.AvailableStates.Add(new SelectListItem
			{
				Text = "全部",
				Value = "0"
			});
			Type enumState = typeof(MaintenanceStateEnum);
			Enum.GetNames(enumState).ToList().ForEach(s =>
			{
				string value = Enum.Format(enumState, Enum.Parse(enumState, s), "d");
				model.AvailableStates.Add(new SelectListItem { Text = s, Value = value });
			});
			model.AvailableIsExternals.Add(new SelectListItem { Text = "全部", Value = "0" });
			model.AvailableIsExternals.Add(new SelectListItem { Text = "是", Value = "1" });
			model.AvailableIsExternals.Add(new SelectListItem { Text = "否", Value = "2" });
			return View(model);
		}

		[HttpPost]
		public virtual ActionResult MaintenanceList(DataSourceRequest command, MaintenanceListModel model)
		{
			if (!_permissionService.Authorize(StandardPermissionProvider.ManageMaintenances))
				return AccessDeniedKendoGridJson();

			var customer = _workContext.CurrentCustomer;

			var categories = _xJMaintenanceService.GetMaintenances(
				customer: customer,
				pNo: model.SearchPNo,
				sNo: model.SearchSNo,
				comment: model.SearchComment,
				planId: model.SearchPlanId,
				placeId: model.SearchPlaceId,
				place: model.SearchPlaceName,
				categoryId: model.SearchCategoryId,
				category: model.SearchCategoryName,
				equipmentName: model.SearchEquipmentName,
				responsibleDepartmentId: model.SearchResponsibleDepartmentId,
				responsibleTeamId: model.SearchResponsibleTeamId,
				responsiblePersonId: model.SearchResponsiblePersonId,
				maintenancePersonId: model.SearchMaintenancePersonId,
				departmentId: model.SearchDepartId,
				customerId: model.SearchUserId,
				isAssign: model.SearchIsAssign,
				isExternal: GetBoolNullable(model.SearchIsExternalId),
				createdFrom: model.SearchCreatedFrom,
				createdTo: model.SearchCreatedTo,
				state: model.SearchState,
				pageIndex: command.Page - 1,
				pageSize: command.PageSize);
			var gridModel = new DataSourceResult
			{
				Data = categories.Select(x =>
				{
					if (x.Details.Any())
						x.EquipmentNames = string.Join(",", x.Details.Select(d => d.Name));
					x.StateName = Enum.GetName(typeof(MaintenanceStateEnum), x.State);
					x.HoursString = GetHoursString(x.Hours);
					return x;
				}),
				Total = categories.TotalCount
			};
			return Json(gridModel);
		}

		[HttpPost, ActionName("List")]
		[FormValueRequired("exportmaintenanceexcel-all")]
		public virtual ActionResult ExportMaintenanceExcelAll(MaintenanceListModel model)
		{
			if (!_permissionService.Authorize(StandardPermissionProvider.ManageMaintenances))
				return AccessDeniedView();

			var customer = _workContext.CurrentCustomer;

			var items = _xJMaintenanceService.GetMaintenances(
				customer: customer,
				pNo: model.SearchPNo,
				sNo: model.SearchSNo,
				comment: model.SearchComment,
				planId: model.SearchPlanId,
				placeId: model.SearchPlaceId,
				place: model.SearchPlaceName,
				categoryId: model.SearchCategoryId,
				category: model.SearchCategoryName,
				equipmentName: model.SearchEquipmentName,
				responsibleDepartmentId: model.SearchResponsibleDepartmentId,
				responsibleTeamId: model.SearchResponsibleTeamId,
				responsiblePersonId: model.SearchResponsiblePersonId,
				maintenancePersonId: model.SearchMaintenancePersonId,
				departmentId: model.SearchDepartId,
				customerId: model.SearchUserId,
				isAssign: model.SearchIsAssign,
				isExternal: GetBoolNullable(model.SearchIsExternalId),
				createdFrom: model.SearchCreatedFrom,
				createdTo: model.SearchCreatedTo,
				state: model.SearchState);

			try
			{
				foreach (var x in items)
				{
					if (x.Details.Any())
						x.EquipmentNames = string.Join(",", x.Details.Select(d => d.Name));
					x.StateName = Enum.GetName(typeof(MaintenanceStateEnum), x.State);
					x.HoursString = GetHoursString(x.Hours);
				}
				byte[] bytes = _exportManager.ExportMaintenanceToXlsx(items);
				return File(bytes, MimeTypes.TextXlsx, "维修记录.xlsx");
			}
			catch (Exception exc)
			{
				ErrorNotification(exc);
				return RedirectToAction("List");
			}
		}

		public virtual ActionResult MyList()
		{
			if (!_permissionService.Authorize(StandardPermissionProvider.ManageMyMaintenances))
				return AccessDeniedView();

			var model = new MaintenanceListModel();

			var customer = _workContext.CurrentCustomer;
			model.OperationLevel = GetLevel(customer);

			model.AvailableDepartments.Add(new SelectListItem
			{
				Text = "全部",
				Value = "0"
			});
			model.AvailableDepartmentMenus.Add(new SelectMenuModel
			{
				name = "全部",
				id = 0,
				open = true,
			});
			var departments = _departmentService.GetAllDepartments(showHidden: false);
			foreach (var d in departments)
				model.AvailableDepartmentMenus.Add(new SelectMenuModel { name = d.Name, id = d.Id, pId = d.PId });
			foreach (var d in departments.Where(m => m.PId == 0))
				model.AvailableDepartments.Add(new SelectListItem { Text = d.Name, Value = d.Id.ToString() });
			model.AvailableUsers.Add(new SelectListItem
			{
				Text = "全部",
				Value = "0"
			});
			var users = _customerService.GetAllCustomers().Select(x => new { id = x.Id, name = x.TrueName ?? x.Username }).ToList();
			foreach (var item in users)
				model.AvailableUsers.Add(new SelectListItem { Text = item.name, Value = item.id.ToString() });
			//if (model.OperationLevel == (int)OperationLevelEnum.审核)
			//{
			//	var users = _customerService.GetAllCustomers(
			//		departId: customer.TeamId
			//		).Select(x => new { id = x.Id, name = x.TrueName ?? x.Username }).ToList();
			//	foreach (var item in users)
			//		model.AvailableUsers.Add(new SelectListItem { Text = item.name, Value = item.id.ToString() });
			//}

			model.AvailableStates.Add(new SelectListItem
			{
				Text = "全部",
				Value = "0"
			});
			Type enumState = typeof(MaintenanceStateEnum);
			Enum.GetNames(enumState).ToList().ForEach(s =>
			{
				string value = Enum.Format(enumState, Enum.Parse(enumState, s), "d");
				model.AvailableStates.Add(new SelectListItem { Text = s, Value = value });
			});
			model.AvailableIsExternals.Add(new SelectListItem { Text = "全部", Value = "0" });
			model.AvailableIsExternals.Add(new SelectListItem { Text = "是", Value = "1" });
			model.AvailableIsExternals.Add(new SelectListItem { Text = "否", Value = "2" });
			return View(model);
		}

		[HttpPost]
		public virtual ActionResult MyMaintenanceList(DataSourceRequest command, MaintenanceListModel model)
		{
			if (!_permissionService.Authorize(StandardPermissionProvider.ManageMyMaintenances))
				return AccessDeniedKendoGridJson();

			var customer = _workContext.CurrentCustomer;

			var categories = _xJMaintenanceService.GetMaintenances(
				customer: customer,
				pNo: model.SearchPNo,
				sNo: model.SearchSNo,
				comment: model.SearchComment,
				planId: model.SearchPlanId,
				placeId: model.SearchPlaceId,
				place: model.SearchPlaceName,
				categoryId: model.SearchCategoryId,
				category: model.SearchCategoryName,
				equipmentName: model.SearchEquipmentName,
				responsibleDepartmentId: model.SearchResponsibleDepartmentId,
				responsibleTeamId: model.SearchResponsibleTeamId,
				responsiblePersonId: model.SearchResponsiblePersonId,
				maintenancePersonId: model.SearchMaintenancePersonId,
				departmentId: model.SearchDepartId,
				customerId: customer.Id,
				isAssign: model.SearchIsAssign,
				isExternal: GetBoolNullable(model.SearchIsExternalId),
				createdFrom: model.SearchCreatedFrom,
				createdTo: model.SearchCreatedTo,
				state: model.SearchState,
				pageIndex: command.Page - 1,
				pageSize: command.PageSize);
			var gridModel = new DataSourceResult
			{
				Data = categories.Select(x =>
				{
					if (x.Details.Any())
						x.EquipmentNames = string.Join(",", x.Details.Select(d => d.Name));
					x.StateName = Enum.GetName(typeof(MaintenanceStateEnum), x.State);
					x.HoursString = GetHoursString(x.Hours);
					return x;
				}),
				Total = categories.TotalCount
			};
			return Json(gridModel);
		}

		[HttpPost, ActionName("MyList")]
		[FormValueRequired("exportmymaintenanceexcel-all")]
		public virtual ActionResult ExportMyMaintenanceExcelAll(MaintenanceListModel model)
		{
			if (!_permissionService.Authorize(StandardPermissionProvider.ManageMyMaintenances))
				return AccessDeniedView();

			var customer = _workContext.CurrentCustomer;

			var items = _xJMaintenanceService.GetMaintenances(
				customer: customer,
				pNo: model.SearchPNo,
				sNo: model.SearchSNo,
				comment: model.SearchComment,
				planId: model.SearchPlanId,
				placeId: model.SearchPlaceId,
				place: model.SearchPlaceName,
				categoryId: model.SearchCategoryId,
				category: model.SearchCategoryName,
				equipmentName: model.SearchEquipmentName,
				responsibleDepartmentId: model.SearchResponsibleDepartmentId,
				responsibleTeamId: model.SearchResponsibleTeamId,
				responsiblePersonId: model.SearchResponsiblePersonId,
				maintenancePersonId: model.SearchMaintenancePersonId,
				departmentId: model.SearchDepartId,
				customerId: customer.Id,
				isAssign: model.SearchIsAssign,
				isExternal: GetBoolNullable(model.SearchIsExternalId),
				createdFrom: model.SearchCreatedFrom,
				createdTo: model.SearchCreatedTo,
				state: model.SearchState);

			try
			{
				foreach (var x in items)
				{
					if (x.Details.Any())
						x.EquipmentNames = string.Join(",", x.Details.Select(d => d.Name));
					x.StateName = Enum.GetName(typeof(MaintenanceStateEnum), x.State);
					x.HoursString = GetHoursString(x.Hours);
				}
				byte[] bytes = _exportManager.ExportMaintenanceToXlsx(items);
				return File(bytes, MimeTypes.TextXlsx, "报修记录.xlsx");
			}
			catch (Exception exc)
			{
				ErrorNotification(exc);
				return RedirectToAction("MyList");
			}
		}

		#endregion

		#region Edit / Delete

		public virtual ActionResult Edit(int id)
		{
			if (!_permissionService.Authorize(StandardPermissionProvider.ManageMaintenances))
				return AccessDeniedView();

			var maintenance = _xJMaintenanceService.GetXJMaintenanceById(id);
			if (maintenance == null || maintenance.Deleted)
				//No equipment found with the specified id
				return RedirectToAction("List");

			var model = new MaintenanceModel
			{
				Id = maintenance.Id,
				InspectionPlanId = maintenance.InspectionPlanId,
				SNo = maintenance.SNo,
				PlaceId = maintenance.PlaceId,
				PlaceName = maintenance.PlaceName,
				CategoryId = maintenance.CategoryId,
				CategoryName = maintenance.CategoryName,
				Comment = maintenance.Comment,
				ResponsibleDepartmentId = maintenance.ResponsibleDepartmentId,
				ResponsibleDepartmentName = maintenance.ResponsibleDepartmentName,
				ResponsibleTeamId = maintenance.ResponsibleTeamId,
				ResponsibleTeamName = maintenance.ResponsibleTeamName,
				ResponsiblePersonId = maintenance.ResponsiblePersonId,
				ResponsiblePersonName = maintenance.ResponsiblePersonName,
				MaintenancePersonNames = maintenance.MaintenancePersonNames,
				MaintenanceComment = maintenance.MaintenanceComment,
				MaintenanceOn = maintenance.MaintenanceOn,
				Star = maintenance.Star,
				Evaluation = maintenance.Evaluation,
				EvaluationOn = maintenance.EvaluationOn,
				State = maintenance.State,
				CustomerId = maintenance.Id,
				CustomerName = maintenance.CustomerName,
				DepartmentName = maintenance.DepartmentName,
				CreatedOn = maintenance.CreatedOn
			};
			model.StateName = Enum.GetName(typeof(MaintenanceStateEnum), maintenance.State);
			model.Hours = maintenance.Minutes;
			model.HoursString = GetHoursString(model.Hours);
			//categories
			PrepareAllTypesModel(model);

			return View(model);
		}

		[HttpPost, ParameterBasedOnFormName("save-continue", "continueEditing")]
		public virtual ActionResult Edit(MaintenanceModel model, bool continueEditing)
		{
			if (!_permissionService.Authorize(StandardPermissionProvider.ManageMaintenances))
				return AccessDeniedView();

			var equipment = _xJMaintenanceService.GetXJMaintenanceById(model.Id);
			if (equipment == null || equipment.Deleted)
				//No equipment found with the specified id
				return RedirectToAction("List");

			if (ModelState.IsValid)
			{
				equipment.ResponsibleDepartmentId = model.ResponsibleDepartmentId;
				equipment.ResponsibleTeamId = model.ResponsibleTeamId;
				equipment.ResponsiblePersonId = model.ResponsiblePersonId;
				equipment.MaintenanceComment = model.MaintenanceComment;
				//equipment.MaintenancePersonId = model.MaintenancePersonId;
				//equipment.MaintenanceOn = model.MaintenanceOn;
				_xJMaintenanceService.UpdateXJMaintenance(equipment);

				//activity log
				_customerActivityService.InsertActivity("EditMaintenance", "编辑报修记录：{0}", equipment.Id);

				SuccessNotification("保存成功");
				if (continueEditing)
				{
					//selected tab
					SaveSelectedTabName();

					return RedirectToAction("Edit", new { id = equipment.Id });
				}
				return RedirectToAction("List");
			}
			//categories
			PrepareAllTypesModel(model);

			return View(model);
		}

		public virtual ActionResult View(int id, string formPage = "List")
		{
			if (!_permissionService.Authorize(StandardPermissionProvider.ManageMaintenances) && !_permissionService.Authorize(StandardPermissionProvider.ManageMyMaintenances))
				return AccessDeniedView();

			var maintenance = _xJMaintenanceService.GetXJMaintenanceById(id);
			if (maintenance == null || maintenance.Deleted)
				//No equipment found with the specified id
				return RedirectToAction("List");

			var customer = _workContext.CurrentCustomer;

			var model = new MaintenanceModel
			{
				Id = maintenance.Id,
				InspectionPlanId = maintenance.InspectionPlanId,
				PNo = maintenance.PNo,
				SNo = maintenance.SNo,
				CategoryId = maintenance.CategoryId,
				CategoryName = maintenance.CategoryName,
				PlaceId = maintenance.PlaceId,
				PlaceName = maintenance.PlaceName,
				Comment = maintenance.Comment,
				ResponsibleDepartmentId = maintenance.ResponsibleDepartmentId,
				ResponsibleDepartmentName = maintenance.ResponsibleDepartmentName,
				ResponsibleTeamId = maintenance.ResponsibleTeamId,
				ResponsibleTeamName = maintenance.ResponsibleTeamName,
				ResponsiblePersonId = maintenance.ResponsiblePersonId,
				ResponsiblePersonName = maintenance.ResponsiblePersonName,
				MaintenancePersonNames = maintenance.MaintenancePersonNames,
				MaintenanceComment = maintenance.MaintenanceComment,
				MaintenanceOn = maintenance.MaintenanceOn,
				Star = maintenance.Star,
				Evaluation = maintenance.Evaluation,
				EvaluationOn = maintenance.EvaluationOn,
				State = maintenance.State,
				CustomerId = maintenance.Id,
				CustomerName = maintenance.CustomerName,
				DepartmentName = maintenance.DepartmentName,
				CreatedOn = maintenance.CreatedOn,
				IsPause = maintenance.IsPause,
				IsAssign = maintenance.IsAssign,
				AssignComment = maintenance.AssignComment,
				IsExternal = maintenance.IsExternal,
				Total = maintenance.Total,
			};

			if (customer.IsAdmin())
			{
				model.CanConfirm = true;
				model.CanAssign = true;
				model.CanAllocate = true;
			}
			if (!model.CanAssign && customer.IsResponsibleLeader())
			{
				model.CanAssign = true;
			}
			if (!model.CanAllocate && customer.IsDepartmentManager())
			{
				model.CanConfirm = true;
				model.CanAllocate = true;
			}
			if (customer.IsRepairman() && maintenance.ResponsibleTeamId > 0 && (maintenance.ResponsibleTeamId == customer.TeamId || maintenance.ResponsibleTeamId == customer.DepartmentId))
			{
				if (maintenance.ResponsiblePersonId == 0 || maintenance.ResponsiblePersonId == customer.Id)
					model.CanComplete = true;
			}
			if (maintenance.CustomerId == customer.Id)
			{
				model.CanComment = true;
			}
			model.StateName = Enum.GetName(typeof(MaintenanceStateEnum), maintenance.State);
			model.Hours = maintenance.Minutes;
			model.HoursString = GetHoursString(model.Hours);

			var pictures = maintenance.GetAttribute<string>("Pictures");
			if (!string.IsNullOrEmpty(pictures))
			{
				var pictureIds = pictures
					.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
					.Select(x => Convert.ToInt32(x))
					.ToArray();
				foreach (var p in pictureIds)
				{
					model.Pictures.Add(_pictureService.GetPictureUrl(p));
				}
			}
			//categories
			PrepareAllTypesModel(model);

			if (formPage == "List" && !_permissionService.Authorize(StandardPermissionProvider.ManageMaintenances))
				formPage = "MyList";
			ViewBag.formPage = formPage;
			return View(model);
		}

		[HttpPost]
		public virtual ActionResult Delete(int id)
		{
			if (!_permissionService.Authorize(StandardPermissionProvider.ManageMaintenances))
				return AccessDeniedView();

			var equipment = _xJMaintenanceService.GetXJMaintenanceById(id);
			if (equipment == null)
				//No equipment found with the specified id
				return RedirectToAction("List");

			_xJMaintenanceService.DeleteMaintenance(equipment);

			//activity log
			_customerActivityService.InsertActivity("DeleteMaintenance", "删除报修记录：{0}", equipment.Id);

			SuccessNotification("删除成功");
			return RedirectToAction("List");
		}

		#endregion

		#region 维修设备明细

		[HttpPost]
		public virtual ActionResult Details(DataSourceRequest command, int maintenanceId)
		{
			if (!_permissionService.Authorize(StandardPermissionProvider.ManageMaintenances) && !_permissionService.Authorize(StandardPermissionProvider.ManageMyMaintenances))
				return AccessDeniedKendoGridJson();

			var details = _xJMaintenanceDetailService.GetXJMaintenanceDetails(
					maintenanceId: maintenanceId,
					pageIndex: command.Page - 1,
					pageSize: command.PageSize);

			var gridModel = new DataSourceResult
			{
				Data = details.Select(x =>
				{
					return x;
				}),
				Total = details.Count(),
			};

			return Json(gridModel);
		}
		public virtual ActionResult DetailDelete(int id)
		{
			if (!_permissionService.Authorize(StandardPermissionProvider.ManageMaintenances) && !_permissionService.Authorize(StandardPermissionProvider.ManageMyMaintenances))
				return AccessDeniedView();

			var detail = _xJMaintenanceDetailService.GetXJMaintenanceDetailById(id);
			if (null != detail)
			{
				var maintenance = _xJMaintenanceService.GetXJMaintenanceById(detail.MaintenanceId);
				if (maintenance != null && maintenance.State <= (int)MaintenanceStateEnum.待维修)
				{
					_xJMaintenanceDetailService.DeleteXJMaintenanceDetail(detail);
				}
			}

			return new NullJsonResult();
		}

		#endregion

		#region 维修工时明细

		[HttpPost]
		public virtual ActionResult Schedules(DataSourceRequest command, int maintenanceId)
		{
			if (!_permissionService.Authorize(StandardPermissionProvider.ManageMaintenances) && !_permissionService.Authorize(StandardPermissionProvider.ManageMyMaintenances))
				return AccessDeniedKendoGridJson();

			var details = _xJMaintenanceScheduleService.GetXJMaintenanceSchedules(
					maintenanceId: maintenanceId,
					pageIndex: command.Page - 1,
					pageSize: command.PageSize);

			int minutes = _xJMaintenanceScheduleService.GetTotalMinutes(maintenanceId: maintenanceId);
			var gridModel = new DataSourceResult
			{
				ExtraData = new { Minutes = minutes },
				Data = details.Select(x =>
				{
					return x;
				}),
				Total = details.Count(),
			};

			return Json(gridModel);
		}
		public virtual ActionResult ScheduleDelete(int id)
		{
			if (!_permissionService.Authorize(StandardPermissionProvider.ManageMaintenances) && !_permissionService.Authorize(StandardPermissionProvider.ManageMyMaintenances))
				return AccessDeniedView();

			var schedule = _xJMaintenanceScheduleService.GetXJMaintenanceScheduleById(id);
			if (null != schedule)
			{
				_xJMaintenanceScheduleService.DeleteXJMaintenanceSchedule(schedule);
			}

			return new NullJsonResult();
		}

		#endregion

		#region Pop

		public virtual ActionResult AddPopup(int planId)
		{
			if (!_permissionService.Authorize(StandardPermissionProvider.ManageInspections))
				return AccessDeniedView();

			var plan = _xJInspectionPlanService.GetXJInspectionPlanById(planId);

			var model = new MaintenanceModel
			{
				PNo = null == plan ? "" : plan.PNo,
				SNo = _xJMaintenanceService.GenerateNo(),
				InspectionPlanId = planId,
				State = (int)MaintenanceStateEnum.保存
			};

			PrepareAllTypesModel(model);

			return View(model);
		}

		[HttpPost]
		[FormValueRequired("save")]
		public virtual ActionResult AddPopup(string btnId, string formId, MaintenanceModel model)
		{
			if (!_permissionService.Authorize(StandardPermissionProvider.ManageInspections))
				return AccessDeniedView();

			if (ModelState.IsValid)
			{
				//if (model.InspectionId > 0)
				//{
				//	var customer = _workContext.CurrentCustomer;
				//	var inspection = _xJInspectionService.GetXJInspectionById(model.InspectionId);
				//	if (null != inspection)
				//	{
				//		var maintenance = new XJMaintenance
				//		{
				//			SNo = _xJMaintenanceService.GenerateNo(),
				//			InspectionPlanId = inspection.InspectionPlanId,
				//			TeamId = model.TeamId,
				//			PersonId = model.PersonId,
				//			//MaintenancePersonId = model.MaintenancePersonId,
				//			//MaintenanceOn = model.MaintenanceOn,
				//			MaintenanceComment = model.MaintenanceComment,
				//			State = model.TeamId > 0 ? (int)MaintenanceStateEnum.待维修 : (int)MaintenanceStateEnum.待分配,
				//			CustomerId = customer.Id,
				//			CreatedOn = DateTime.Now,
				//		};
				//		_xJMaintenanceService.InsertXJMaintenance(maintenance);

				//		var maintenanceComment = new XJMaintenanceComment
				//		{
				//			MaintenanceId = maintenance.Id,
				//			TypeId = maintenance.State == (int)MaintenanceStateEnum.待维修 ? (int)MaintenanceCommentTypeEnum.维修分配 : (int)MaintenanceCommentTypeEnum.维修申请,
				//			CustomerId = customer.Id,
				//			CreatedOn = DateTime.Now,
				//		};
				//		_xJMaintenanceCommentService.InsertXJMaintenanceComment(maintenanceComment);

				//		_xJInspectionService.UpdateXJInspection(inspection);
				//	}
				//}

				ViewBag.RefreshPage = true;
				ViewBag.btnId = btnId;
				ViewBag.formId = formId;
			}
			//categories
			PrepareAllTypesModel(model);
			return View(model);
		}

		public virtual ActionResult EditPopup(int id)
		{
			if (!_permissionService.Authorize(StandardPermissionProvider.ManageInspections))
				return AccessDeniedView();

			var model = new MaintenanceModel();
			var maintenance = _xJMaintenanceService.GetXJMaintenanceById(id);
			if (maintenance != null && !maintenance.Deleted)
			{
				model = new MaintenanceModel
				{
					Id = maintenance.Id,
					InspectionPlanId = maintenance.InspectionPlanId,
					PNo = maintenance.PNo,
					SNo = maintenance.SNo,
					PlaceId = maintenance.PlaceId,
					PlaceName = maintenance.PlaceName,
					CategoryId = maintenance.CategoryId,
					CategoryName = maintenance.CategoryName,
					Comment = maintenance.Comment,
					ResponsibleDepartmentId = maintenance.ResponsibleDepartmentId,
					ResponsibleDepartmentName = maintenance.ResponsibleDepartmentName,
					ResponsibleTeamId = maintenance.ResponsibleTeamId,
					ResponsibleTeamName = maintenance.ResponsibleTeamName,
					ResponsiblePersonId = maintenance.ResponsiblePersonId,
					ResponsiblePersonName = maintenance.ResponsiblePersonName,
					MaintenancePersonNames = maintenance.MaintenancePersonNames,
					MaintenanceComment = maintenance.MaintenanceComment,
					MaintenanceOn = maintenance.MaintenanceOn,
					Star = maintenance.Star,
					Evaluation = maintenance.Evaluation,
					EvaluationOn = maintenance.EvaluationOn,
					State = maintenance.State,
					CustomerId = maintenance.Id,
					CustomerName = maintenance.CustomerName,
					DepartmentName = maintenance.DepartmentName,
					CreatedOn = maintenance.CreatedOn
				};
				model.StateName = Enum.GetName(typeof(MaintenanceStateEnum), maintenance.State);
				model.Hours = maintenance.Minutes;
				model.HoursString = GetHoursString(model.Hours);

				var pictures = maintenance.GetAttribute<string>("Pictures");
				if (!string.IsNullOrEmpty(pictures))
				{
					var pictureIds = pictures
						.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
						.Select(x => Convert.ToInt32(x))
						.ToArray();
					foreach (var p in pictureIds)
					{
						model.Pictures.Add(_pictureService.GetPictureUrl(p));
					}
				}
			}
			//categories
			PrepareAllTypesModel(model);
			return View(model);
		}

		[HttpPost]
		[FormValueRequired("save")]
		public virtual ActionResult EditPopup(string btnId, string formId, MaintenanceModel model)
		{
			if (!_permissionService.Authorize(StandardPermissionProvider.ManageInspections))
				return AccessDeniedView();

			if (ModelState.IsValid)
			{
				var maintenance = _xJMaintenanceService.GetXJMaintenanceById(model.Id);
				if (maintenance != null && !maintenance.Deleted)
				{
					maintenance.ResponsibleDepartmentId = model.ResponsibleDepartmentId;
					maintenance.ResponsibleTeamId = model.ResponsibleTeamId;
					maintenance.ResponsiblePersonId = model.ResponsiblePersonId;
					maintenance.MaintenanceComment = model.MaintenanceComment;
					//equipment.MaintenancePersonId = model.MaintenancePersonId;
					//equipment.MaintenanceOn = model.MaintenanceOn;
					_xJMaintenanceService.UpdateXJMaintenance(maintenance);

					//activity log
					_customerActivityService.InsertActivity("EditMaintenance", "编辑报修记录：{0}", maintenance.Id);

				}
				ViewBag.RefreshPage = true;
				ViewBag.btnId = btnId;
				ViewBag.formId = formId;
			}
			//categories
			PrepareAllTypesModel(model);

			return View(model);
		}

		#endregion

		#region Equipments
		/// <summary>
		/// 设施设备列表
		/// </summary>
		/// <param name="command"></param>
		/// <param name="maintenanceId"></param>
		/// <returns></returns>
		[HttpPost]
		public virtual ActionResult EquipmentList(DataSourceRequest command, EquipmentStockListModel model)
		{
			if (!_permissionService.Authorize(StandardPermissionProvider.ManageMaintenances))
				return AccessDeniedKendoGridJson();

			var stocks = _xJEquipmentStockService.GetAllStocks(
				categoryId: model.SearchCategoryId,
				placeId: model.SearchPlaceId,
				equipmentId: model.SearchEquipmentId,
				name: model.SearchName,
				location: model.SearchLocation,
				pageIndex: command.Page - 1,
				pageSize: command.PageSize);

			var stockIds = _xJMaintenanceDetailService.GetXJMaintenanceDetails(model.MaintenanceId).Select(x => x.EquipmentStockId).ToArray();
			var gridModel = new DataSourceResult
			{
				Data = stocks.Select(x =>
				{
					x.Checked = stockIds != null && stockIds.Length > 0 && stockIds.Contains(x.Id);
					return x;
				}),
				Total = stocks.TotalCount
			};

			return Json(gridModel);
		}

		public virtual ActionResult EquipmentAddPopup(int maintenanceId)
		{
			if (!_permissionService.Authorize(StandardPermissionProvider.ManageMaintenances))
				return AccessDeniedView();

			var model = new EquipmentStockListModel
			{
				MaintenanceId = maintenanceId
			};

			model.AvailableCategories.Add(new SelectMenuModel
			{
				name = "全部",
				id = 0,
				open = true,
			});
			var categorys = _xJEquipmentCategoryService.GetAllCategorys(isConsumables: false, showHidden: false);
			foreach (var c in categorys)
				model.AvailableCategories.Add(new SelectMenuModel { name = c.Name, id = c.Id, pId = c.PId });
			model.AvailablePlaces.Add(new SelectListItem
			{
				Text = "全部",
				Value = "0"
			});
			var places = _xjPlaceService.GetAllPlaces(showHidden: false);
			foreach (var p in places)
				model.AvailablePlaces.Add(new SelectListItem { Text = p.Name, Value = p.Id.ToString() });
			return View(model);
		}

		[HttpPost]
		[FormValueRequired("save")]
		public virtual ActionResult EquipmentAddPopup(string btnId, string formId, EquipmentStockListModel model)
		{
			if (!_permissionService.Authorize(StandardPermissionProvider.ManageMaintenances))
				return AccessDeniedView();

			if (model.MaintenanceId > 0)
			{
				var maintenance = _xJMaintenanceService.GetXJMaintenanceById(model.MaintenanceId);
				if (null != maintenance)
				{
					var details = _xJMaintenanceDetailService.GetXJMaintenanceDetails(maintenance.Id);
					if (details.Any())
					{
						if (model.SelectedProductIds == null || model.SelectedProductIds.Length == 0)
						{
							foreach (var detail in details)
							{
								_xJMaintenanceDetailService.DeleteXJMaintenanceDetail(detail);
							}
						}
						else
						{
							foreach (var detail in details.Where(m => !model.SelectedProductIds.Contains(m.EquipmentStockId)))
							{
								_xJMaintenanceDetailService.DeleteXJMaintenanceDetail(detail);
							}
						}
						if (model.SelectedProductIds != null && model.SelectedProductIds.Length > 0)
						{
							var stocks = _xJEquipmentStockService.GetStocksByIds(model.SelectedProductIds);
							foreach (var stock in stocks)
							{
								if (!details.Any(m => m.EquipmentStockId == stock.Id))
								{
									_xJMaintenanceDetailService.InsertXJMaintenanceDetail(new XJMaintenanceDetail
									{
										MaintenanceId = maintenance.Id,
										EquipmentStockId = stock.Id,
										EquipmentId = stock.EquipmentId,
										Name = stock.Name,
										Manufacturer = stock.Manufacturer,
										Specification = stock.Specification,
										Location = stock.Location
									});
								}
							}
						}
					}
					else
					{
						if (model.SelectedProductIds != null && model.SelectedProductIds.Length > 0)
						{
							var stocks = _xJEquipmentStockService.GetStocksByIds(model.SelectedProductIds);
							if (stocks.Any())
							{
								foreach (var stock in stocks)
								{
									_xJMaintenanceDetailService.InsertXJMaintenanceDetail(new XJMaintenanceDetail
									{
										MaintenanceId = maintenance.Id,
										EquipmentStockId = stock.Id,
										EquipmentId = stock.EquipmentId,
										Name = stock.Name,
										Manufacturer = stock.Manufacturer,
										Specification = stock.Specification,
										Location = stock.Location
									});
								}
							}
						}
					}
				}
			}

			ViewBag.RefreshPage = true;
			ViewBag.btnId = btnId;
			ViewBag.formId = formId;
			return View(model);
		}

		#endregion

		#region Comment

		[HttpPost]
		public virtual ActionResult CommentList(DataSourceRequest command, MaintenanceCommentListModel model)
		{
			if (!_permissionService.Authorize(StandardPermissionProvider.ManageMaintenances) && !_permissionService.Authorize(StandardPermissionProvider.ManageMyMaintenances))
				return AccessDeniedKendoGridJson();

			var comments = _xJMaintenanceCommentService.GetAllMaintenanceComments(
				maintenanceId: model.SearchMaintenanceId,
				pageIndex: command.Page - 1,
				pageSize: command.PageSize);
			var gridModel = new DataSourceResult
			{
				Data = comments.Select(x =>
				{
					var comment = new MaintenanceCommentModel
					{
						Id = x.Id,
						MaintenanceId = x.MaintenanceId,
						TypeId = x.TypeId,
						TypeName = Enum.GetName(typeof(MaintenanceCommentTypeEnum), x.TypeId),
						PId = x.PId,
						Comment = x.Comment,
						Star = x.Star,
						CustomerId = x.CustomerId,
						CustomerName = _customerService.GetNameById(x.CustomerId),
						CreatedOn = x.CreatedOn,
					};
					return comment;
				}),
				Total = comments.TotalCount
			};
			return Json(gridModel);
		}

		/// <summary>
		/// 暂停/启动
		/// </summary>
		/// <param name="id"></param>
		/// <param name="isStart">启动</param>
		/// <returns></returns>
		[HttpPost]
		public virtual ActionResult Pause(int id, bool isStart = false, string content = "")
		{
			if (!_permissionService.Authorize(StandardPermissionProvider.ManageMaintenances))
				return AccessDeniedView();

			var maintenance = _xJMaintenanceService.GetXJMaintenanceById(id);
			if (maintenance == null)
				return Json(new { result = false, msg = "报修记录无效" });

			if (maintenance.State != (int)MaintenanceStateEnum.待维修)
				return Json(new { result = false, msg = "不是待维修状态" });

			var customer = _workContext.CurrentCustomer;

			var result = _xJMaintenanceService.Pause(xJMaintenanceId: id, customer: customer, isStart: isStart, comment: content);
			if (!result.Result)
			{
				return Json(new { result = false, msg = result.Msg });
			}

			var comment = new XJMaintenanceComment
			{
				MaintenanceId = maintenance.Id,
				TypeId = isStart ? (int)MaintenanceCommentTypeEnum.维修启动 : (int)MaintenanceCommentTypeEnum.维修暂停,
				Comment = string.Format("{0} {1}", isStart ? "启动" : "暂停", content),
				CustomerId = customer.Id,
				CreatedOn = DateTime.Now,
			};
			_xJMaintenanceCommentService.InsertXJMaintenanceComment(comment);

			//activity log
			_customerActivityService.InsertActivity("PauseMaintenance", "{0}：{1}", isStart ? "启动" : "暂停", maintenance.Id);
			return Json(new { result = true });
		}

		[HttpPost]
		public virtual ActionResult Complete(int id, bool isExternal = false, decimal total = 0)
		{
			if (!_permissionService.Authorize(StandardPermissionProvider.ManageMaintenances))
				return AccessDeniedView();

			var maintenance = _xJMaintenanceService.GetXJMaintenanceById(id);
			if (maintenance == null)
				return Json(new { result = false, msg = "报修记录无效" });

			if (maintenance.IsPause)
				return Json(new { result = false, msg = "报修暂停" });

			var customer = _workContext.CurrentCustomer;

			var outs = _xJEquipmentStockOutService.GetAllStockOuts(maintenanceId: maintenance.Id, state: (int)StockOutStateEnum.待审核);
			if (outs.Any())
				return Json(new { result = false, msg = "领用申请未完结" });

			var result = _xJMaintenanceService.Complete(xJMaintenanceId: id, customer: customer, isExternal: isExternal, total: total);
			if (!result.Result)
			{
				return Json(new { result = false, msg = result.Msg });
			}

			var comment = new XJMaintenanceComment
			{
				MaintenanceId = maintenance.Id,
				TypeId = (int)MaintenanceCommentTypeEnum.完工汇报,
				CustomerId = customer.Id,
				CreatedOn = DateTime.Now,
			};
			_xJMaintenanceCommentService.InsertXJMaintenanceComment(comment);

			//activity log
			_customerActivityService.InsertActivity("CompleteMaintenance", "完工：{0}", maintenance.Id);
			return Json(new { result = true });
		}

		public virtual ActionResult AddCommentPopup(int maintenanceId)
		{
			if (!_permissionService.Authorize(StandardPermissionProvider.ManageMaintenances) && !_permissionService.Authorize(StandardPermissionProvider.ManageMyMaintenances))
				return AccessDeniedView();

			var model = new MaintenanceCommentModel
			{
				MaintenanceId = maintenanceId,
				TypeId = (int)MaintenanceCommentTypeEnum.维修评价,
				Star = 100
			};

			return View(model);
		}

		[HttpPost]
		[FormValueRequired("save")]
		public virtual ActionResult AddCommentPopup(string btnId, string formId, MaintenanceCommentModel model)
		{
			if (!_permissionService.Authorize(StandardPermissionProvider.ManageMaintenances) && !_permissionService.Authorize(StandardPermissionProvider.ManageMyMaintenances))
				return AccessDeniedView();

			var customer = _workContext.CurrentCustomer;
			if (model.MaintenanceId > 0)
			{
				var maintenance = _xJMaintenanceService.GetXJMaintenanceById(model.MaintenanceId);
				if (null != maintenance)
				{
					if (maintenance.State == (int)MaintenanceStateEnum.待评价)
					{
						var comment = new XJMaintenanceComment
						{
							MaintenanceId = maintenance.Id,
							TypeId = (int)MaintenanceCommentTypeEnum.维修评价,
							Comment = model.Comment,
							Star = model.Star,
							CustomerId = customer.Id,
							CreatedOn = DateTime.Now,
						};
						_xJMaintenanceCommentService.InsertXJMaintenanceComment(comment);

						maintenance.Star = model.Star;
						maintenance.Evaluation = model.Comment;
						maintenance.State = (int)MaintenanceStateEnum.已完工;
						_xJMaintenanceService.UpdateXJMaintenance(maintenance);
					}
				}
			}

			ViewBag.RefreshPage = true;
			ViewBag.btnId = btnId;
			ViewBag.formId = formId;
			return View(model);
		}

		/// <summary>
		/// 确认
		/// </summary>
		/// <param name="maintenanceId"></param>
		/// <returns></returns>
		public virtual ActionResult AddConfirmPopup(int maintenanceId)
		{
			if (!_permissionService.Authorize(StandardPermissionProvider.ManageMaintenances))
				return AccessDeniedView();

			var model = new MaintenanceAllocatModel
			{
				MaintenanceId = maintenanceId
			};
			var maintenance = _xJMaintenanceService.GetXJMaintenanceById(model.MaintenanceId);
			if (null != maintenance)
			{
				model.AvailableDepartments.Add(new SelectListItem
				{
					Text = "全部",
					Value = maintenance.ResponsibleDepartmentId.ToString()
				});
				if (maintenance.ResponsibleDepartmentId > 0)
				{
					var departments = _departmentService.GetAllDepartments(
						pid: maintenance.ResponsibleDepartmentId,
						showHidden: false,
						isMaintenance: true);
					foreach (var c in departments)
					{
						model.AvailableDepartments.Add(new SelectListItem
						{
							Text = c.Name,
							Value = c.Id.ToString()
						});
					}
				}

				model.ResponsibleTeamId = maintenance.ResponsibleTeamId;
				var maintenancePersons = _xJMaintenanceCustomersService.GetMaintenanceCustomerss(maintenance.Id);
				if (maintenancePersons.Any())
				{
					model.MaintenancePersonIds = maintenancePersons.Select(p => p.Id).ToList();
				}

				var users = _customerService.GetAllCustomers(
						customerRoleIds: new int[] { _customerService.GetCustomerRoleBySystemName(SystemCustomerRoleNames.Repairman).Id },
						departId: maintenance.ResponsibleDepartmentId,
						showHidden: false
					).ToList();
				foreach (var u in users)
				{
					model.AvailableMaintenanceUsers.Add(new SelectListItem
					{
						Text = u.TrueName ?? u.Username,
						Value = u.Id.ToString(),
						Selected = model.MaintenancePersonIds.Contains(u.Id)
					});
				}
			}


			return View(model);
		}

		[HttpPost, ParameterBasedOnFormName("save-pass", "pass")]
		public virtual ActionResult AddConfirmPopup(string btnId, string formId, MaintenanceAllocatModel model, bool pass)
		{
			if (!_permissionService.Authorize(StandardPermissionProvider.ManageMaintenances))
				return AccessDeniedView();

			var customer = _workContext.CurrentCustomer;
			if (model.MaintenanceId > 0)
			{
				var maintenance = _xJMaintenanceService.GetXJMaintenanceById(model.MaintenanceId);
				if (null != maintenance && !maintenance.Deleted && maintenance.State == (int)MaintenanceStateEnum.待确认)
				{
					if (pass)
					{
						if (model.ResponsibleTeamId == 0)
							model.ResponsibleTeamId = maintenance.ResponsibleDepartmentId;

						var depart = _departmentService.GetDepartmentById(model.ResponsibleTeamId);
						if (null != depart)
						{
							var users = _customerService.GetAllCustomers(
									customerRoleIds: new int[] { _customerService.GetCustomerRoleBySystemName(SystemCustomerRoleNames.Repairman).Id },
									teamId: depart.Id
								);

							var maintenancePersons = _xJMaintenanceCustomersService.GetMaintenanceCustomerss(maintenance.Id);
							if (maintenancePersons.Any())
							{
								// 清除责任人
								maintenance.ResponsiblePersonId = 0;
								maintenance.ResponsiblePersonName = null;
								foreach (var item in maintenancePersons)
								{
									_xJMaintenanceCustomersService.DeleteXJMaintenanceCustomers(item);
								}
							}

							string maintenancePersonNames = "";
							var names = new List<string>();
							if (model.MaintenancePersonIds.Any())
							{
								foreach (var id in model.MaintenancePersonIds)
								{
									var u = users.FirstOrDefault(m => m.Id == id);
									if (null != u)
									{
										// 第一个为责任人
										if (maintenance.ResponsiblePersonId == 0)
										{
											maintenance.ResponsiblePersonId = u.Id;
											maintenance.ResponsiblePersonName = u.TrueName;
										}
										names.Add(u.TrueName);
										_xJMaintenanceCustomersService.InsertXJMaintenanceCustomers(new XJMaintenanceCustomers
										{
											MaintenanceId = maintenance.Id,
											CustomerId = u.Id,
											CustomerName = u.TrueName
										});
									}
								}
								maintenancePersonNames = string.Join(",", names);
							}

							maintenance.ResponsibleTeamId = depart.Id;
							maintenance.ResponsibleTeamName = depart.Name;
							maintenance.MaintenancePersonNames = CommonHelper.EnsureMaximumLength(maintenancePersonNames, 50, "...");
							maintenance.State = (int)MaintenanceStateEnum.待维修;
							_xJMaintenanceService.UpdateXJMaintenance(maintenance);

							// 分配时新增维修时间表，截止时计算工时
							_xJMaintenanceScheduleService.NewSchedule(new XJMaintenanceSchedule
							{
								MaintenanceId = maintenance.Id,
								StartOn = DateTime.Now,
								StartCustomer = customer.TrueName,
							});

							var comment = new XJMaintenanceComment
							{
								MaintenanceId = maintenance.Id,
								TypeId = (int)MaintenanceCommentTypeEnum.维修分配,
								Comment = string.Format("分配-->{0}{1}", depart.Name, maintenancePersonNames),
								CustomerId = customer.Id,
								CreatedOn = DateTime.Now,
							};
							_xJMaintenanceCommentService.InsertXJMaintenanceComment(comment);
						}
					}
					else
					{
						maintenance.ResponsibleDepartmentId = 0;
						maintenance.ResponsibleDepartmentName = null;
						maintenance.ResponsibleTeamId = 0;
						maintenance.ResponsibleTeamName = null;
						maintenance.ResponsiblePersonId = 0;
						maintenance.ResponsiblePersonName = null;
						maintenance.State = (int)MaintenanceStateEnum.待指派;
						_xJMaintenanceService.UpdateXJMaintenance(maintenance);

						var comment = new XJMaintenanceComment
						{
							MaintenanceId = maintenance.Id,
							TypeId = (int)MaintenanceCommentTypeEnum.申请指派,
							Comment = "申请指派-->",
							CustomerId = customer.Id,
							CreatedOn = DateTime.Now,
						};
						_xJMaintenanceCommentService.InsertXJMaintenanceComment(comment);
					}
				}
			}

			ViewBag.RefreshPage = true;
			ViewBag.btnId = btnId;
			ViewBag.formId = formId;
			return View(model);
		}

		/// <summary>
		/// 指派
		/// </summary>
		/// <param name="maintenanceId"></param>
		/// <returns></returns>
		public virtual ActionResult AddAssignPopup(int maintenanceId)
		{
			if (!_permissionService.Authorize(StandardPermissionProvider.ManageMaintenances))
				return AccessDeniedView();

			var model = new MaintenanceAssignModel
			{
				MaintenanceId = maintenanceId
			};

			var departments = _departmentService.GetAllDepartments(pid: 0, showHidden: false, isMaintenance: true);
			foreach (var c in departments)
			{
				model.AvailableDepartments.Add(new SelectListItem
				{
					Text = c.Name,
					Value = c.Id.ToString()
				});
			}
			var maintenance = _xJMaintenanceService.GetXJMaintenanceById(model.MaintenanceId);
			if (null != maintenance)
			{
				model.ResponsibleDepartmentId = maintenance.ResponsibleDepartmentId;
				model.ResponsibleDepartmentName = maintenance.ResponsibleDepartmentName;
			}

			return View(model);
		}

		[HttpPost]
		[FormValueRequired("save")]
		public virtual ActionResult AddAssignPopup(string btnId, string formId, MaintenanceAssignModel model)
		{
			if (!_permissionService.Authorize(StandardPermissionProvider.ManageMaintenances))
				return AccessDeniedView();

			var customer = _workContext.CurrentCustomer;
			if (model.MaintenanceId > 0 && model.ResponsibleDepartmentId > 0)
			{
				var maintenance = _xJMaintenanceService.GetXJMaintenanceById(model.MaintenanceId);
				if (null != maintenance && !maintenance.Deleted && maintenance.State == (int)MaintenanceStateEnum.待指派)
				{
					var depart = _departmentService.GetDepartmentById(model.ResponsibleDepartmentId);
					if (null != depart)
					{
						maintenance.ResponsibleDepartmentId = depart.Id;
						maintenance.ResponsibleDepartmentName = depart.Name;
						maintenance.IsAssign = true;
						maintenance.AssignComment = model.AssignComment;
						maintenance.State = (int)MaintenanceStateEnum.待分配;
						_xJMaintenanceService.UpdateXJMaintenance(maintenance);

						var comment = new XJMaintenanceComment
						{
							MaintenanceId = maintenance.Id,
							TypeId = (int)MaintenanceCommentTypeEnum.维修指派,
							Comment = string.Format("指派-->{0}", depart.Name),
							CustomerId = customer.Id,
							CreatedOn = DateTime.Now,
						};
						_xJMaintenanceCommentService.InsertXJMaintenanceComment(comment);

						// 所有的指派都必须经过部门负责人才能变更为待维修
						//// 如果选中的部门没有下级维修班组，默认当前部门为维修班组
						//if (!_departmentService.GetAllDepartments(pid:depart.Id,showHidden:false,isMaintenance:true).Any())
						//{
						//	//ErrorNotification("指定的部门没有维修班组");
						//	maintenance.ResponsibleTeamId = depart.Id;
						//	maintenance.ResponsibleTeamName = depart.Name;
						//	maintenance.State = (int)MaintenanceStateEnum.待维修;
						//}
					}
				}
			}

			ViewBag.RefreshPage = true;
			ViewBag.btnId = btnId;
			ViewBag.formId = formId;
			return View(model);
		}

		/// <summary>
		/// 分配
		/// </summary>
		/// <param name="maintenanceId"></param>
		/// <returns></returns>
		public virtual ActionResult AddAllocatePopup(int maintenanceId)
		{
			if (!_permissionService.Authorize(StandardPermissionProvider.ManageMaintenances))
				return AccessDeniedView();

			var model = new MaintenanceAllocatModel
			{
				MaintenanceId = maintenanceId
			};
			var maintenance = _xJMaintenanceService.GetXJMaintenanceById(model.MaintenanceId);
			if (null != maintenance)
			{
				model.AvailableDepartments.Add(new SelectListItem
				{
					Text = "全部",
					Value = maintenance.ResponsibleDepartmentId.ToString()
				});
				if (maintenance.ResponsibleDepartmentId > 0)
				{
					var departments = _departmentService.GetAllDepartments(pid: maintenance.ResponsibleDepartmentId, showHidden: false, isMaintenance: true);
					foreach (var c in departments)
					{
						model.AvailableDepartments.Add(new SelectListItem
						{
							Text = c.Name,
							Value = c.Id.ToString()
						});
					}
				}

				model.ResponsibleTeamId = maintenance.ResponsibleTeamId;
				var maintenancePersons = _xJMaintenanceCustomersService.GetMaintenanceCustomerss(maintenance.Id);
				if (maintenancePersons.Any())
				{
					model.MaintenancePersonIds = maintenancePersons.Select(p => p.Id).ToList();
				}

				var users = _customerService.GetAllCustomers(
						customerRoleIds: new int[] { _customerService.GetCustomerRoleBySystemName(SystemCustomerRoleNames.Repairman).Id },
						departId: maintenance.ResponsibleDepartmentId
					).ToList();
				foreach (var u in users)
				{
					model.AvailableMaintenanceUsers.Add(new SelectListItem
					{
						Text = u.TrueName ?? u.Username,
						Value = u.Id.ToString(),
						Selected = model.MaintenancePersonIds.Contains(u.Id)
					});
				}
			}


			return View(model);
		}

		[HttpPost]
		[FormValueRequired("save")]
		public virtual ActionResult AddAllocatePopup(string btnId, string formId, MaintenanceAllocatModel model)
		{
			if (!_permissionService.Authorize(StandardPermissionProvider.ManageMaintenances))
				return AccessDeniedView();

			var customer = _workContext.CurrentCustomer;
			if (model.MaintenanceId > 0)
			{
				var maintenance = _xJMaintenanceService.GetXJMaintenanceById(model.MaintenanceId);
				if (null != maintenance && maintenance.State == (int)MaintenanceStateEnum.待分配)
				{
					if (model.ResponsibleTeamId == 0)
						model.ResponsibleTeamId = maintenance.ResponsibleDepartmentId;

					var depart = _departmentService.GetDepartmentById(model.ResponsibleTeamId);
					if (null != depart)
					{
						var users = _customerService.GetAllCustomers(
								customerRoleIds: new int[] { _customerService.GetCustomerRoleBySystemName(SystemCustomerRoleNames.Repairman).Id },
								teamId: depart.Id
							);

						var maintenancePersons = _xJMaintenanceCustomersService.GetMaintenanceCustomerss(maintenance.Id);
						if (maintenancePersons.Any())
						{
							// 清除责任人
							maintenance.ResponsiblePersonId = 0;
							maintenance.ResponsiblePersonName = null;
							foreach (var item in maintenancePersons)
							{
								_xJMaintenanceCustomersService.DeleteXJMaintenanceCustomers(item);
							}
						}

						string maintenancePersonNames = "";
						var names = new List<string>();
						if (model.MaintenancePersonIds != null && model.MaintenancePersonIds.Any())
						{
							foreach (var id in model.MaintenancePersonIds)
							{
								var u = users.FirstOrDefault(m => m.Id == id);
								if (null != u)
								{
									// 第一个为责任人
									if (maintenance.ResponsiblePersonId == 0)
									{
										maintenance.ResponsiblePersonId = u.Id;
										maintenance.ResponsiblePersonName = u.TrueName;
									}
									names.Add(u.TrueName);
									_xJMaintenanceCustomersService.InsertXJMaintenanceCustomers(new XJMaintenanceCustomers
									{
										MaintenanceId = maintenance.Id,
										CustomerId = u.Id,
										CustomerName = u.TrueName
									});
								}
							}
							maintenancePersonNames = string.Join(",", names);
						}

						maintenance.ResponsibleTeamId = depart.Id;
						maintenance.ResponsibleTeamName = depart.Name;
						maintenance.MaintenancePersonNames = CommonHelper.EnsureMaximumLength(maintenancePersonNames, 50, "...");
						maintenance.State = (int)MaintenanceStateEnum.待维修;
						_xJMaintenanceService.UpdateXJMaintenance(maintenance);

						// 分配时新增维修时间表，截止时计算工时
						_xJMaintenanceScheduleService.NewSchedule(new XJMaintenanceSchedule
						{
							MaintenanceId = maintenance.Id,
							StartOn = DateTime.Now,
							StartCustomer = customer.TrueName,
						});

						var comment = new XJMaintenanceComment
						{
							MaintenanceId = maintenance.Id,
							TypeId = (int)MaintenanceCommentTypeEnum.维修分配,
							Comment = string.Format("分配-->{0}{1}", depart.Name, maintenancePersonNames),
							CustomerId = customer.Id,
							CreatedOn = DateTime.Now,
						};
						_xJMaintenanceCommentService.InsertXJMaintenanceComment(comment);

					}
				}
			}

			ViewBag.RefreshPage = true;
			ViewBag.btnId = btnId;
			ViewBag.formId = formId;
			return View(model);
		}

		#endregion

		[ChildActionOnly]
		public virtual ActionResult Statistics()
		{
			if (!_permissionService.Authorize(StandardPermissionProvider.ManageReports))
				return Content("");

			return PartialView();
		}

		[AcceptVerbs(HttpVerbs.Get)]
		public virtual ActionResult LoadStatistics(string period)
		{
			if (!_permissionService.Authorize(StandardPermissionProvider.ManageReports))
				return Content("");

			var result = new List<object>();

			var nowDt = _dateTimeHelper.ConvertToUserTime(DateTime.Now);
			var timeZone = _dateTimeHelper.CurrentTimeZone;

			var culture = new CultureInfo(_workContext.WorkingLanguage.LanguageCulture);

			switch (period)
			{
				case "year":
					//year statistics
					var yearAgoDt = nowDt.AddYears(-1).AddMonths(1);
					var searchYearDateUser = new DateTime(yearAgoDt.Year, yearAgoDt.Month, 1);
					if (!timeZone.IsInvalidTime(searchYearDateUser))
					{
						for (int i = 0; i <= 12; i++)
						{
							result.Add(new
							{
								date = searchYearDateUser.Date.ToString("Y", culture),
								value = _xJMaintenanceService.GetAllMaintenances(
									createdFrom: _dateTimeHelper.ConvertToUtcTime(searchYearDateUser, timeZone),
									createdTo: _dateTimeHelper.ConvertToUtcTime(searchYearDateUser.AddMonths(1), timeZone),
									pageIndex: 0,
									pageSize: 1).TotalCount.ToString()
							});

							searchYearDateUser = searchYearDateUser.AddMonths(1);
						}
					}
					break;

				case "month":
					//month statistics
					var monthAgoDt = nowDt.AddDays(-30);
					var searchMonthDateUser = new DateTime(monthAgoDt.Year, monthAgoDt.Month, monthAgoDt.Day);
					if (!timeZone.IsInvalidTime(searchMonthDateUser))
					{
						for (int i = 0; i <= 30; i++)
						{
							result.Add(new
							{
								date = searchMonthDateUser.Date.ToString("M", culture),
								value = _xJMaintenanceService.GetAllMaintenances(
									createdFrom: _dateTimeHelper.ConvertToUtcTime(searchMonthDateUser, timeZone),
									createdTo: _dateTimeHelper.ConvertToUtcTime(searchMonthDateUser.AddDays(1), timeZone),
									pageIndex: 0,
									pageSize: 1).TotalCount.ToString()
							});

							searchMonthDateUser = searchMonthDateUser.AddDays(1);
						}
					}
					break;

				case "week":
				default:
					//week statistics
					var weekAgoDt = nowDt.AddDays(-7);
					var searchWeekDateUser = new DateTime(weekAgoDt.Year, weekAgoDt.Month, weekAgoDt.Day);
					if (!timeZone.IsInvalidTime(searchWeekDateUser))
					{
						for (int i = 0; i <= 7; i++)
						{
							result.Add(new
							{
								date = searchWeekDateUser.Date.ToString("d dddd", culture),
								value = _xJMaintenanceService.GetAllMaintenances(
									createdFrom: _dateTimeHelper.ConvertToUtcTime(searchWeekDateUser, timeZone),
									createdTo: _dateTimeHelper.ConvertToUtcTime(searchWeekDateUser.AddDays(1), timeZone),
									pageIndex: 0,
									pageSize: 1).TotalCount.ToString()
							});

							searchWeekDateUser = searchWeekDateUser.AddDays(1);
						}
					}
					break;
			}

			return Json(result, JsonRequestBehavior.AllowGet);
		}

		public virtual ActionResult ReportByUserList()
		{
			if (!_permissionService.Authorize(StandardPermissionProvider.ManageReports))
				return Content("");

			var model = new ReportByUserListModel();

			model.AvailableDepartmentMenus.Add(new SelectMenuModel
			{
				name = "全部",
				id = 0,
				open = true,
			});
			model.AvailableUsers.Add(new SelectListItem
			{
				Text = "全部",
				Value = "0"
			});
			var departments = _departmentService.GetAllDepartments(
				showHidden: false,
				isMaintenance: true);
			foreach (var d in departments)
				model.AvailableDepartmentMenus.Add(new SelectMenuModel { name = d.Name, id = d.Id, pId = d.PId });

			var users = _customerService.GetAllCustomers(
					customerRoleIds: new int[] { _customerService.GetCustomerRoleBySystemName(SystemCustomerRoleNames.Repairman).Id },
					showHidden: false
				).ToList();
			foreach (var u in users)
			{
				model.AvailableUsers.Add(new SelectListItem
				{
					Text = u.TrueName ?? u.Username,
					Value = u.Id.ToString()
				});
			}
			return View(model);
		}

		public virtual ActionResult ReportByUser()
		{
			if (!_permissionService.Authorize(StandardPermissionProvider.ManageReports))
				return Content("");

			return PartialView();
		}
		[HttpPost]
		public virtual ActionResult ReportByUsers(DataSourceRequest command, ReportByUserListModel model)
		{
			if (!_permissionService.Authorize(StandardPermissionProvider.ManageReports))
				return AccessDeniedKendoGridJson();

			int year = 0, month = 0;
			var hours = new List<CustomerHours>();
			if (model.SearchMonth.HasValue)
			{
				year = model.SearchMonth.Value.Year;
				month = model.SearchMonth.Value.Month;
				hours = _customerService.GetCustomerHours(
					year: year,
					month: month,
					departmentId: model.SearchDepartId,
					customerId: model.SearchUserId
					).ToList();
			}

			var items = _xJMaintenanceService.GetReportByUser(
				year: year,
				month: month,
				departmentId: model.SearchDepartId,
				customerId: model.SearchUserId,
				pageIndex: command.Page - 1,
				pageSize: command.PageSize);

			var total = _xJMaintenanceService.GetTotalByUser(
				year: year,
				month: month,
				departmentId: model.SearchDepartId,
				customerId: model.SearchUserId);
			if (null != total)
			{
				total.HoursString = GetHoursString(total.Hours);
			}
			var gridModel = new DataSourceResult
			{
				ExtraData = total,
				Data = items.Select(x =>
				{
					x.HoursString = GetHoursString(x.Hours);
					x.Per = GetPer(x.Hours, x.Amount);
					var hour = hours.FirstOrDefault(m => m.CustomerId == x.CustomerId);
					if (null != hour)
					{
						x.MonthHours = hour.Hours > 0 ? string.Format("{0}时", hour.Hours) : "";
						x.Efficiency = GetEfficiency(x.Hours, hour.Hours);
					}
					return x;
				}),
				Total = items.TotalCount
			};

			return Json(gridModel);
		}

		[HttpPost, ActionName("ReportByUserList")]
		[FormValueRequired("exportbyuserexcel-all")]
		public virtual ActionResult ExportByUserExcelAll(ReportByUserListModel model)
		{
			if (!_permissionService.Authorize(StandardPermissionProvider.ManageReports))
				return AccessDeniedView();

			int year = 0, month = 0;
			var hours = new List<CustomerHours>();
			if (model.SearchMonth.HasValue)
			{
				year = model.SearchMonth.Value.Year;
				month = model.SearchMonth.Value.Month;
				hours = _customerService.GetCustomerHours(
					year: year,
					month: month,
					departmentId: model.SearchDepartId,
					customerId: model.SearchUserId
					).ToList();
			}

			var items = _xJMaintenanceService.GetReportByUser(
				year: year,
				month: month,
				departmentId: model.SearchDepartId,
				customerId: model.SearchUserId);

			try
			{
				foreach (var x in items)
				{
					x.HoursString = GetHoursString(x.Hours);
					x.Per = GetPer(x.Hours, x.Amount);
					var hour = hours.FirstOrDefault(m => m.CustomerId == x.CustomerId);
					if (null != hour)
					{
						x.MonthHours = hour.Hours > 0 ? string.Format("{0}时", hour.Hours) : "";
						x.Efficiency = GetEfficiency(x.Hours, hour.Hours);
					}
				}
				byte[] bytes = _exportManager.ExportMaintenanceReportByUserToXlsx(items);
				return File(bytes, MimeTypes.TextXlsx, "维修人员统计.xlsx");
			}
			catch (Exception exc)
			{
				ErrorNotification(exc);
				return RedirectToAction("ReportByUserList");
			}
		}

		public virtual ActionResult ReportByEquipmentList()
		{
			if (!_permissionService.Authorize(StandardPermissionProvider.ManageReports))
				return Content("");

			var model = new ReportByUserListModel();

			model.AvailableDepartmentMenus.Add(new SelectMenuModel
			{
				name = "全部",
				id = 0,
				open = true,
			});
			model.AvailableUsers.Add(new SelectListItem
			{
				Text = "全部",
				Value = "0"
			});
			var departments = _departmentService.GetAllDepartments(
				showHidden: false,
				isMaintenance: true);
			foreach (var d in departments)
				model.AvailableDepartmentMenus.Add(new SelectMenuModel { name = d.Name, id = d.Id, pId = d.PId });

			var users = _customerService.GetAllCustomers(
					customerRoleIds: new int[] { _customerService.GetCustomerRoleBySystemName(SystemCustomerRoleNames.Repairman).Id },
					showHidden: false
				).ToList();
			foreach (var u in users)
			{
				model.AvailableUsers.Add(new SelectListItem
				{
					Text = u.TrueName ?? u.Username,
					Value = u.Id.ToString()
				});
			}
			return View(model);
		}

		public virtual ActionResult ReportByEquipment()
		{
			if (!_permissionService.Authorize(StandardPermissionProvider.ManageReports))
				return Content("");

			return PartialView();
		}
		[HttpPost]
		public virtual ActionResult ReportByEquipments(DataSourceRequest command, ReportByUserListModel model)
		{
			if (!_permissionService.Authorize(StandardPermissionProvider.ManageReports))
				return AccessDeniedKendoGridJson();

			int year = 0, month = 0;
			if (model.SearchMonth.HasValue)
			{
				year = model.SearchMonth.Value.Year;
				month = model.SearchMonth.Value.Month;
			}
			var items = _xJMaintenanceService.GetReportByEquipment(
				year: year,
				month: month,
				departmentId: model.SearchDepartId,
				customerId: model.SearchUserId,
				pageIndex: command.Page - 1,
				pageSize: command.PageSize);
			var total = _xJMaintenanceService.GetTotalByEquipment(
				year: year,
				month: month,
				departmentId: model.SearchDepartId,
				customerId: model.SearchUserId);
			if (null != total)
			{
				total.HoursString = GetHoursString(total.Hours);
			}
			var gridModel = new DataSourceResult
			{
				ExtraData = total,
				Data = items.Select(x =>
				{
					x.HoursString = GetHoursString(x.Hours);
					x.Per = GetPer(x.Hours, x.Amount);
					return x;
				}),
				Total = items.TotalCount
			};

			return Json(gridModel);
		}

		[HttpPost, ActionName("ReportByEquipmentList")]
		[FormValueRequired("exportbyequipmentexcel-all")]
		public virtual ActionResult ExportByEquipmentExcelAll(ReportByUserListModel model)
		{
			if (!_permissionService.Authorize(StandardPermissionProvider.ManageReports))
				return AccessDeniedView();

			int year = 0, month = 0;
			if (model.SearchMonth.HasValue)
			{
				year = model.SearchMonth.Value.Year;
				month = model.SearchMonth.Value.Month;
			}
			var items = _xJMaintenanceService.GetReportByEquipment(
				year: year,
				month: month,
				departmentId: model.SearchDepartId,
				customerId: model.SearchUserId);

			try
			{
				foreach (var x in items)
				{
					x.HoursString = GetHoursString(x.Hours);
					x.Per = GetPer(x.Hours, x.Amount);
				}
				byte[] bytes = _exportManager.ExportMaintenanceReportByEquipmentToXlsx(items);
				return File(bytes, MimeTypes.TextXlsx, "维修设备统计.xlsx");
			}
			catch (Exception exc)
			{
				ErrorNotification(exc);
				return RedirectToAction("ReportByEquipmentList");
			}
		}

	}
}